<template>
  <el-card>
    <el-button type="primary" class="new-btn" @click="showAddNewActivity()">
      <el-icon>
        <font-awesome-icon :icon="['fas', 'plus']" />
      </el-icon>
      开启新活动
    </el-button>

    <div class="table">
      <!-- 表格 -->
      <el-table v-loading="loading" :data="activityList" style="width: 100%">
        <el-table-column v-for="item in activityTableLabel" :key="item.prop" :label="item.label" :prop="item.prop"
          :width="item.width" :sortable="item.sortable" />
        <!-- 活动资金 -->
        <el-table-column prop="fund" label="补贴资金 / 元">
          <template v-slot="scope">
            {{ scope.row.fund.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 活动满 -->
        <el-table-column prop="reach" label="活动满 / 元">
          <template v-slot="scope">
            {{ scope.row.reach.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 活动减 -->
        <el-table-column prop="reduce" label="活动减 / 元">
          <template v-slot="scope">
            {{ scope.row.reduce.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 活动当前余额 -->
        <el-table-column prop="balance" label="当前余额 / 元">
          <template v-slot="scope">
            {{ scope.row.balance.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 活动状态 -->
        <el-table-column :filters="[{ text: '进行中', value: 1 }, { text: '已失效', value: 0 }]" prop="status" label="活动状态"
          :filter-method="filterTag" width="95">
          <template v-slot="scope">
            <el-tag size="small" v-if="scope.row.status === 1" type="success">进行中</el-tag>
            <el-tag size="small" v-else-if="scope.row.status === 0" type="danger">已失效</el-tag>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="getactivityDetail(scope.$index)">详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background layout="prev, pager, next" :total="config.total" class="pager mt-4"
        @current-change="changePage" :page-size="config.size" />
    </div>
  </el-card>

  <!-- 查看活动详情的模态框 -->
  <el-dialog v-model="dialogVisible" title="查看活动详情" width="50%" align-center>

    <!-- 商店详细信息展示表格 -->
    <el-descriptions :column="1" size="default" border v-loading="detail_loading">
      <el-descriptions-item min-width="130px" label="活动ID" label-align="center" align="center">
        {{ activityDetail.activity.activityId }}
      </el-descriptions-item>
      <el-descriptions-item label="活动名称" label-align="center" align="center">
        {{ activityDetail.activity.activityName }}
      </el-descriptions-item>
      <el-descriptions-item v-if="currentCategoryList.length == activityDetail.activity.categoryIdList.length"
        label="商品类型" label-align="center" align="center">
        <el-tag v-for="item in currentCategoryList" type="info" style="margin-right: 5px; margin-top:5px;">{{
          item.categoryName }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="补贴资金 / 元" label-align="center" align="center">
        {{ activityDetail.activity.fund.toFixed(2) }}
      </el-descriptions-item>
      <el-descriptions-item label="开始时间" label-align="center" align="center">
        {{ activityDetail.activity.startTime }}
      </el-descriptions-item>
      <el-descriptions-item label="结束时间" label-align="center" align="center">
        {{ activityDetail.activity.endTime }}
      </el-descriptions-item>
      <el-descriptions-item label="活动满减" label-align="center" align="center">
        满
        <span style="font-size: 18px; color: #2e64c2;">
          {{ activityDetail.activity.reach.toFixed(2) }}
        </span>
        元立减
        <span style="font-size: 18px; color: #2e64c2;">
          {{ activityDetail.activity.reduce.toFixed(2) }}
        </span>
        元
      </el-descriptions-item>
      <el-descriptions-item label="剩余资金 / 元" label-align="center" align="center" :span="2">
        {{ activityDetail.activity.balance.toFixed(2) }}
      </el-descriptions-item>
      <el-descriptions-item label="活动状态" label-align="center" align="center" :span="2">
        <el-tag size="large" v-if="activityDetail.activity.status === 1" type="success">进行中</el-tag>
        <el-tag size="large" v-else-if="activityDetail.activity.status === 0" type="danger">已失效</el-tag>
      </el-descriptions-item>
    </el-descriptions>

    <h1 style="font-size: 17px; margin-bottom: 10px; margin-top: 30px;">
      活动参与限制
      <span style="font-size: 13px; margin-left: 10px; color: #666666;">
        <font-awesome-icon :icon="['fas', 'circle-info']" />
        注：参与活动商店的注册资金、月销量、月销售额，需要大于下列要求值。
      </span>
    </h1>

    <el-descriptions :column="1" direction="vertical" size="default" border v-loading="detail_loading">
      <el-descriptions-item label="注册资金 / 元" align="center" :span="2">
        {{ activityDetail.activity.registeredCapital.toFixed(2) }}
      </el-descriptions-item>
      <el-descriptions-item label="月销量 / 件" align="center" :span="2">
        {{ activityDetail.activity.monthlySalesVolume }}
      </el-descriptions-item>
      <el-descriptions-item label="月销售额 / 元" align="center" :span="2">
        {{ activityDetail.activity.monthlySalesValue.toFixed(2) }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 底部的按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 开启新活动的模态框 -->
  <el-dialog v-model="dialogVisible2" title="开启新活动" width="50%" align-center>
    <el-form v-loading="new_activity_loading" ref="newActivityFormRef" :model="newActivity.activity" label-width="120px"
      :rules="rules" status-icon>
      <!-- 活动名 -->
      <el-form-item prop="activityName" label="活动名称">
        <el-input input-style="text-align: center;" style="width: 83%;" v-model="newActivity.activity.activityName" />
      </el-form-item>

      <!-- 活动资金 -->
      <el-form-item prop="fund" label="活动资金">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="2" :controls="false" style="width: 83%;" v-model="newActivity.activity.fund"
          :max="10000000.00" />
      </el-form-item>

      <!-- 开始时间-结束时间 -->
      <el-form-item prop="time" label="时间范围" style="width: 85.5%;">
        <el-date-picker v-model="datetime_range" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
          :default-time="defaultTime1" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>

      <!-- 活动商品类别 -->
      <el-form-item prop="categoryIdList" label="活动商品类型" class="category" style="width: 85%;">
        <div>
          <select-category @confirm="confirm" class="select"></select-category>
          <!-- 动态标签 -->
          <div>
            <el-tag class="tag" v-for="(tag, index) in currentNewActivityCategoryList" :key="tag.categoryId" closable
              :disable-transitions="false" @close="handleClose(index)">
              {{ tag.categoryName }}
            </el-tag>
          </div>
        </div>
      </el-form-item>

      <!-- 满足金额 -->
      <el-form-item prop="reach" label="活动满金额">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="2" :controls="false" style="width: 83%;" v-model="newActivity.activity.reach"
          :max="10000000.00" />
      </el-form-item>

      <!-- 减少金额 -->
      <el-form-item prop="reduce" label="活动减金额">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="2" :controls="false" style="width: 83%;" v-model="newActivity.activity.reduce"
          :max="10000000.00" />
      </el-form-item>

      <!-- 注册资金 -->
      <el-form-item prop="registeredCapital" label="注册资金要求">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="2" :controls="false" style="width: 83%;"
          v-model="newActivity.activity.registeredCapital" :max="10000000.00" />
      </el-form-item>

      <!-- 月销量 -->
      <el-form-item prop="monthlySalesVolume" label="月销量要求">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="0" :controls="false" style="width: 83%;"
          v-model="newActivity.activity.monthlySalesVolume" :max="10000000" />
      </el-form-item>

      <!-- 月销售额 -->
      <el-form-item prop="monthlySalesValue" label="月销售额要求">
        <!-- 利用element-plus自带的数字输入 -->
        <el-input-number :precision="2" :controls="false" style="width: 83%;"
          v-model="newActivity.activity.monthlySalesValue" :max="10000000.00" />
      </el-form-item>

    </el-form>

    <!-- 底部的按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="submitNewActivity">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, reactive } from 'vue';
import { registeredCapital } from '../../../validator';
import SelectCategory from '../../../components/SelectCategory.vue'
import { moreThanZero } from '../../../validator/index'

const { proxy } = getCurrentInstance();
const activityList = ref([]);
const currentCategoryList = ref([]);  // 当前打开的活动详情的类别
const currentNewActivityCategoryList = ref([
  {
    "categoryId": "",
    "categoryName": ""
  }
]);  // 当前添加新活动的商品类别列表
const detailIndex = ref(0);  // 当前查看详情的商品索引
const loading = ref(false);  // 控制表格加载遮罩窗是否出现
const detail_loading = ref(false);  // 控制活动详情模态框中内容的加载
const new_activity_loading = ref(false);
const dialogVisible = ref(false);  // 控制模态框的显示和隐藏
const dialogVisible2 = ref(false);
const newActivityFormRef = ref();
const defaultTime1 = new Date(2000, 1, 1, 12, 0, 0);  // '12:00:00'
const datetime_range = ref([]);  // 绑定时间范围
let activityDetail = reactive({
  activity: {
    "activityId": "",
    "activityName": "",
    "startTime": "",
    "endTime": "",
    "categoryIdList": [],
    "fund": 0,
    "reach": 0,
    "reduce": 0,
    "balance": 0,
    "registeredCapital": 0,
    "monthlySalesVolume": 0,
    "monthlySalesValue": 0.0,
    "status": 0
  }
});
let newActivity = reactive({
  activity: {
    "activityId": "",
    "activityName": "",
    "startTime": "",
    "endTime": "",
    "categoryIdList": [],
    "fund": 0.0,
    "reach": 0.0,
    "reduce": 0.0,
    "balance": 0.0,
    "registeredCapital": 0,
    "monthlySalesVolume": 0,
    "monthlySalesValue": 0.0,
    "status": 1
  }
});

const activityTableLabel = reactive([
  {
    prop: "activityId",
    label: "活动ID",
    width: 180,
    sortable: true,
  },
  {
    prop: "activityName",
    label: "活动名称",
    width: 180
  },
  {
    prop: "startTime",
    label: "开始时间",
    width: 180,
    sortable: true,
  },
  {
    prop: "endTime",
    label: "结束时间",
    width: 180,
    sortable: true,
  },
]);

const config = reactive({
  total: 0,  // 总的条目数
  current: 1,  // 当前页
  size: 15  // 一页的条目数
})

// 表单的校验规则
const rules = reactive({
  activityName: [
    { required: true, message: '请输入活动名', trigger: 'blur' },
  ],
  fund: [
    { required: true, message: '请输入活动资金', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < newActivity.activity.reduce)
          callback(new Error("补贴资金不应当少于满减金额"));
        else
          callback();
      }
    },
  ],
  time: [
    {
      validator: (rule, value, callback) => {
        if (!datetime_range.value || datetime_range.value.length !== 2)
          callback(new Error("请选择活动时间范围"));
        else
          callback()
      },
      trigger: 'blur',
    },
  ],
  registeredCapital: [
    { required: true, message: '请输入注册资金', trigger: 'blur' },
    { validator: registeredCapital, trigger: 'blur' },
  ],
  categoryIdList: [
    {
      validator: (rule, value, callback) => {
        if (currentNewActivityCategoryList.value.length <= 0)
          callback(new Error("请至少选择一种商品类型"));
        else
          callback()
      },
    },
  ],
  reach: [
    { required: true, message: '请输入活动满金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < newActivity.activity.reduce)
          callback(new Error("满金额不应少于减金额"));
        else
          callback()
      }
    },
    { validator: moreThanZero, trigger: 'blur', }
  ],
  reduce: [
    { required: true, message: '请输入活动减金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > newActivity.activity.reach)
          callback(new Error("减金额不应多于满金额"));
        else
          callback()
      }
    }
  ],
  monthlySalesVolume: [
    { required: true, message: '请输入月销量要求', trigger: 'blur' },
  ],
  monthlySalesValue: [
    { required: true, message: '请输入月销售额要求', trigger: 'blur' },
  ]
})

/**
 * 获取活动列表的一页
 */
const getActivityList = async () => {
  // 发起请求
  let res = await proxy.$api.activity.getPageOfAllActivity({
    current: config.current,
    size: config.size,
  });
  // 更新表格数据
  activityList.value = res.data.activityList;
  config.total = res.data.total;
}

/**
 * 翻页
 * @param {number} page 目标页码
 */
const changePage = async (page) => {
  loading.value = true;
  // 更新当前页码
  config.current = page
  await getActivityList()
  loading.value = false;
}

let filterTag = (value, row) => {
  return row.status === value;
}

/**
 * 获取当前活动详情对应的商品类别
 */
const getCurrentActivityCategory = async () => {
  currentCategoryList.value = [];
  for (let i = 0; i < activityDetail.activity.categoryIdList.length; ++i) {
    let ret = await proxy.$api.category.getCategory(activityDetail.activity.categoryIdList[i]);
    currentCategoryList.value.push(ret.data);
  }
}

/**
 * 显示添加新活动的模态框，并进行一些初始化
 */
const showAddNewActivity = () => {
  currentNewActivityCategoryList.value = [];
  dialogVisible2.value = true;
}

/**
 * 下拉框子组件选定了一个类别
 */
const confirm = (category) => {
  let item;
  for (let i = 0; i < currentNewActivityCategoryList.value.length; ++i) {
    item = currentNewActivityCategoryList.value[i];
    if (item.categoryId === category.categoryId) {
      ElMessage.error({ showClose: true, message: "已经选择了该商品类型，请不要重复选择！" });
      return;
    }
  }
  currentNewActivityCategoryList.value.push(category)
}

// 这里直接用索引号找到activityList中的信息即可
const getactivityDetail = async (index) => {
  dialogVisible.value = true;
  detailIndex.value = index;
  activityDetail.activity = activityList.value[index];
  detail_loading.value = true;
  await getCurrentActivityCategory();
  detail_loading.value = false;
}

/**
 * 新增活动模态框中，点击删除商品类别
 */
const handleClose = (index) => {
  currentNewActivityCategoryList.value.splice(index, 1);
}

/**
 * 提交新跨店满减活动
 */
const submitNewActivity = async () => {
  let valid = await newActivityFormRef.value.validate();
  if (valid) {
    newActivity.activity.categoryIdList = [];
    currentNewActivityCategoryList.value.forEach(item => newActivity.activity.categoryIdList.push(item.categoryId));
    newActivity.activity.startTime = datetime_range.value[0];
    newActivity.activity.endTime = datetime_range.value[1];
    newActivity.activity.balance = newActivity.activity.fund;
    let ret = await proxy.$api.activity.launchActivity(newActivity.activity);
    if (ret.status === 200) {
      ElMessage.success({ showClose: true, message: "成功发起一个新的活动" });
    }
  }
}

onMounted(async () => {
  // 开启加载遮罩
  loading.value = true;
  await getActivityList();
  // 关闭加载遮罩
  loading.value = false;
});
</script>

<style lang="less" scoped>
.new-btn {
  margin-bottom: 10px;
}

.table {
  position: relative;

  .pager {
    position: relative;
    bottom: -15px;
    justify-content: flex-end;
    margin-right: 15px;
    margin-top: 10px;
    margin-bottom: 15px;
  }
}

.category {

  .select {
    margin-bottom: 4px;
  }

  .tag {
    margin-left: 4px;
    margin-right: 4px;
    margin-top: 4px;
    margin-bottom: 4px;
  }
}
</style>